package whf.framework.workflow.web;

import whf.framework.entity.AbstractEntity;
import whf.framework.web.struts.WebData;
import whf.framework.web.struts.WebDispatchAction;
import whf.framework.web.struts.WebForward;
import whf.framework.workflow.client.WorkflowClient;
import whf.framework.workflow.entity.WorkflowEntity;
import whf.framework.workflow.exception.WorkflowException;
import whf.framework.workflow.service.WorkflowDefinitionServiceImp;
import whf.framework.workflow.service.WorkflowEntityService;
import whf.framework.workflow.service.WorkflowEntityServiceImp;

/**
 * @author King
 *
 */
@SuppressWarnings("unchecked")
public class WorkflowEntityAction extends WebDispatchAction {

	public WebForward startProcessInstance(AbstractEntity webEntity, WebData data) throws Exception {
		WorkflowEntity workflowEntity = WorkflowEntityServiceImp.getWorkflowEntityService().findByPrimaryKey(webEntity.getId());
		if(workflowEntity.getProcessInstanceId() > 0) {
			throw new WorkflowException("ProcessInstance started already!");
		}
		String username = data.getUserContext().getUser().getUsername();
		WorkflowClient client = WorkflowClient.getWorkflowClient(workflowEntity, username);
		client.startProcessInstance();
		return view(webEntity, data);
	}
	
	public WebForward resetWorkflowDefinition(AbstractEntity webEntity, WebData data) throws Exception {
		WorkflowEntityService service = (WorkflowEntityService)this.getService();
		WorkflowEntity workflowEntity = service.findByPrimaryKey(webEntity.getId());
		if(workflowEntity.getProcessInstanceId() > 0) {
			throw new WorkflowException("ProcessInstance started already!");
		}
		long workflowDefinitionId = data.getLongParameter("workflowDefinitionId", 0);
		if(workflowDefinitionId > 0) {
			workflowEntity.setWorkflowDefinition(WorkflowDefinitionServiceImp.getWorkflowDefinitionService().findByPrimaryKey(workflowDefinitionId));
			service.update(workflowEntity);
		}
		return super.create(webEntity, data);
	}
}
